# -*- encoding:utf-8 -*-
# @time:2022-11-07 21:04
# @Author : serein
# @Email: serein@qq.com
# @File:serializers.py
# @Software: PyCharm



from rest_framework import serializers, status
from rest_framework.fields import SerializerMethodField
from rest_framework.response import Response

from community.models import Article, Comment


class ArticleSerializers(serializers.ModelSerializer):
    user_name = serializers.CharField(source='user.username',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)  # 编写文章的用户头像
    lable_name = serializers.CharField(source='lable.name',read_only=True)
    class Meta:
        model = Article
        exclude = ['is_delete']


class CommentSerializers(serializers.ModelSerializer):
    user_name = serializers.CharField(source='user.id',read_only=True)
    user_article = serializers.CharField(source='user.userdetail.avatar',read_only=True)
    sonComment = SerializerMethodField()  # 添加自定义返回字段 即是下面的哪一个函数返回的字段
    class Meta:
        model = Comment
        exclude = ['is_delete']
    def get_sonComment(self, comment):
        # 这里是让序列化器可以匹配的对相应的子评论  这个也相应的算是调用了sonCommentSerializer的功能
        # 查询父级评论的id
        serializer = SonCommentSerializer(Comment.objects.filter(parent_comment=comment.id), many=True)
        data = serializer.data
        # 这个是将data里面数据颠倒的方法
        data.reverse()
        return data
class SonCommentSerializer(serializers.ModelSerializer):
    user_name = serializers.CharField(source='user.username', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    reply_username = SerializerMethodField()  # 添加自定义返回字段

    class Meta:
        model = Comment
        exclude = ['is_delete']

    def get_reply_username(self, comment):
        # 查询出被回复评论的用户的用户名
        try:
            # 如果没有指明被回复的用户就会报错
            print(comment.reply_comment,11111)
            return Comment.objects.get(id=comment.reply_comment).user.username
        except:
            return '无法查询到数据'

